<template>
    <el-dialog :title="form_title" :visible.sync="isShow" width="46%" :lock-scroll="true" :close-on-click-modal="false">
        <div class="dialog">
            <el-form>
                <el-row :gutter="10">
                    <el-col :span="12" v-for="item in dialogConfig" :key="item">
                        <el-form-item :label="item.placeholder">
                            <el-select
                                v-if="item.type === 'select'"
                                v-model="form1[item.name]"
                                clearable
                                :multiple="item?.multiple ?? false"
                                :placeholder="item.placeholder"
                                @change="
                                    (e) => {
                                        if (item.onChange !== undefined) {
                                            item.onChange(e)
                                        }
                                    }
                                "
                                :readonly="item?.readonly ?? false"
                            >
                                <el-option v-for="k in item.options" :key="k.name" :label="k.name" :value="k.id"></el-option>
                            </el-select>
                            <el-select
                                v-if="item.type === 'select_'"
                                v-model="form1[item.name]"
                                clearable
                                :multiple="item?.multiple ?? false"
                                :placeholder="item.placeholder"
                                @change="
                                    (e) => {
                                        if (item.onChange !== undefined) {
                                            item.onChange(e)
                                        }
                                    }
                                "
                                :readonly="item?.readonly ?? false"
                            >
                                <el-option v-for="k in item.options" :key="k.label" :label="k.label" :value="k.value"></el-option>
                            </el-select>
                            <el-input v-if="item.type === 'input'" :placeholder="item.placeholder" :readonly="item?.readonly ?? false" v-model="form1[item.name]"></el-input>
                            <el-cascader
                                v-if="item.type === 'cascader'"
                                :placeholder="item.placeholder"
                                collapse-tags
                                :options="item.options"
                                :show-all-levels="item?.showAllLevels ?? false"
                                :props="{ checkStrictly: item?.checkStrictly ?? false, multiple: item?.multiple ?? false }"
                                clearable
                                :filterable="item.filterable"
                                v-model="form1[item.name]"
                                @change="
                                    (e) => {
                                        if (item.onChange !== undefined) {
                                            item.onChange(e)
                                        }
                                    }
                                "
                            ></el-cascader>

                            <el-switch
                                v-if="item.type === 'switch'"
                                v-model="form1[item.name]"
                                :active-text="item?.options?.active?.text ?? ''"
                                :inactive-text="item?.options?.inactive?.text ?? ''"
                                :active-value="item?.options?.active?.value ?? ''"
                                :inactive-value="item?.options?.inactive?.value ?? ''"
                                @change="
                                    () => {
                                        if (item.onChange !== undefined) {
                                            item.onChange(dialog.config, dialog.form)
                                        }
                                    }
                                "
                            ></el-switch>

                            <el-input v-if="item.type === 'number'" :placeholder="item.placeholder" :readonly="item?.readonly ?? false" v-model.number="form1[item.name]"></el-input>
                            <el-date-picker
                                v-if="item.type === 'datetime'"
                                :readonly="item?.readonly ?? false"
                                type="datetime"
                                :placeholder="item.placeholder"
                                v-model="form1[item.name]"
                                value-format="yyyy-MM-dd HH:mm:ss"
                            ></el-date-picker>

                            <el-button v-if="item.type === 'button'" @click="item.click" type="primary" size="small">{{ item.text }}</el-button>
                        </el-form-item>
                    </el-col>

                    <cl-col v-if="devices.length != 0 && type == 'add'">
                        <table class="sensor_table" border="1px solid #66B1FF">
                            <tr>
                                <th>设备名称</th>
                            </tr>
                            <tr v-for="(item, index) in devices">
                                <td>{{ item.device_name }}</td>
                            </tr>
                        </table>
                    </cl-col>
                </el-row>
                <el-row :gutter="10" v-if="type == 'add'">
                    <el-col>
                        <el-button @click="setDevice()" type="primary" size="small">选择设备</el-button>
                    </el-col>
                </el-row>
                <el-row :gutter="10" v-if="type != 'view'">
                    <el-col>
                        <el-button type="primary" @click="submit">提交</el-button>
                        <el-button @click="isShow = false">取消</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <el-dialog width="30%" :visible.sync="treeShow" append-to-body :close-on-click-modal="false">
            <el-tree :data="treeData" highlight-current node-key="pid" :show-checkbox="true" :filter-node-method="filterNode" @check-change="handleCheckChange" ref="tree">
                <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span>
                        <i :class="data.icon"></i>
                        {{ node.label }}
                    </span>
                </span>
            </el-tree>
            <div style="margin-top: 10px">
                <el-button type="primary" size="small" @click="getCheckedKeys">确认</el-button>
                <el-button size="small" @click="treeShow = false">取消</el-button>
            </div>
        </el-dialog>
    </el-dialog>
</template>

<script>
import { mapState } from 'vuex'
import { requestApi } from '@/requset/api'
import { deepClone } from '@/plugins/clone'
import { addForm, formatData, editConfig, dialogConfig, viewConfig, arrayToObject, mergeConfigs } from './formConfig.js'
import zyDevice from '@/components/common/zyDevice.vue'
export default {
    data() {
        return {
            isShow: false,
            dialogConfig: null,
            treeShow: false,
            treeData: [],
            checkNodes: [],
            form1: {},
            devices: [],
            form_title: '',
            type: null,
            thrConfig: [],
            sensors: [],
        }
    },
    components: {
        zyDevice,
    },
    props: {
        troubleList: {
            type: Array,
            default: [],
        },
    },
    computed: {
        ...mapState('backstage', ['backstageData', 'sensorType', 'wavcacq', 'sys_eig']),
    },
    methods: {
        handleCheckChange() {
            const nodes = this.$refs.tree.getCheckedNodes()
            const leafNodes = nodes.filter((node) => node.type == 's' && node.checked !== false)
            if (this.channels == 0) return
            else {
                if (this.channels < leafNodes.length) {
                    this.$message.warning('绑定测点数大于通道数!')
                }
            }
        },
        getCheckedKeys() {
            this.devices = []
            const nodes = this.$refs.tree.getCheckedNodes()


            nodes.forEach((e) => {
                if (e.children.length == 0)
                    this.devices.push({
                        device_id: e.value,
                        device_name: e.label,
                    })
            })
            this.treeShow = false
        },
        doOpen(val, type) {
            if (val) {
                if (type == 'view') {
                    this.form_title = '查看'
                    this.type = type
                    this.thrConfig = JSON.parse(deepClone(val).config)

                    let viewConfig1 = deepClone(viewConfig)
                    this.thrConfig.config.forEach((e) => {
                        let name = e.type || 'input'
                        if (name === '') {
                            name = 'input'
                        }
                        let { config_index, config_name } = e
                        viewConfig1.push({
                            name: config_index,
                            type: name,
                            placeholder: config_name,
                        })
                    })
                    viewConfig1.map((e) => (e.readonly = true))
                    this.form1 = arrayToObject(deepClone(this.thrConfig.config))
                    this.form1 = Object.assign(this.form1, val)
                    this.dialogConfig = deepClone(viewConfig1)
                } else if (type == 'edit') {
                    this.form_title = '编辑'
                    this.type = type
                    let { id, device_id } = val
                    this.getSensor(device_id).then(() => {
                        this.thrConfig = JSON.parse(deepClone(val).config)
                        let arr = []
                        this.sensors.forEach((e) => {
                            arr.push({
                                label: e.sensor_name,
                                value: e.id,
                            })
                        })
                        editConfig[0].options = arr
                        let editConfig1 = deepClone(editConfig)
                        this.thrConfig.config.forEach((e) => {
                            let name = e.type || 'input'
                            if (name === '') {
                                name = 'input'
                            }
                            let { config_index, config_name } = e
                            editConfig1.push({
                                name: config_index,
                                type: name,
                                placeholder: config_name,
                            })
                        })
                        editConfig1.push({
                            name: 'istest',
                            type: 'switch',
                            options: {
                                active: { text: '线上', value: 2 },
                                inactive: { text: '测试', value: 1 },
                            },
                            label: '轴数',
                        })
                        this.form1 = arrayToObject(deepClone(this.thrConfig.config))
                        this.form1.id = id
                        if (val.sensor_id) this.$set(this.form1, 'sensor_id', Number(val.sensor_id))
                        this.$set(this.form1, 'channel', val.channel)
                        this.$set(this.form1, 'istest', val.istest)
                        this.dialogConfig = deepClone(editConfig1)
                    })
                }
            } else {
                this.type = 'add'
                this.initConfig()
                this.form1 = deepClone(addForm)
                this.devices = []
                this.form_title = '添加'
            }
            this.$nextTick(() => {
                this.isShow = true
            })
        },
        setDevice() {
            if (this.form1.scope_id_list) var id = this.form1.scope_id_list[this.form1.scope_id_list.length - 1]
            else {
                this.$message.info('请先选择筛选范围')
                return
            }
            if (this.treeData.length == 0) {
                requestApi('get', `sensor/tree/getlist?id=${id}&type=device`, {}, true)
                    .then((res) => {
                        if (res.data.code == 0) {
                            this.treeData = res.data.data
                        }
                    })
                    .then(() => {
                        this.treeShow = true
                    })
            } else this.treeShow = true
        },
        filterNode(value, data) {
            if (!value) return true
            return data.type == 'd' && data.pid == `zone${value}`
        },
        add(obj) {
            requestApi('post', 'algorithm/add', obj, true).then((res) => {
                if (res.data.code == 0) {
                    this.$message.success('添加成功')
                    this.isShow = false
                    this.$emit('search')
                }
            })
        },
        edit(obj) {
            requestApi('post', 'algorithm/edit', obj, true).then((res) => {
                if (res.data.code == 0) {
                    this.$message.success('编辑成功')
                    this.isShow = false
                    this.$emit('search')
                }
            })
        },
        submit() {
            if (this.form_title == '添加') {
                this.form1.devices = this.devices

                this.add(this.form1)
            } else {
                let { id, sensor_id, direction_sensor, channel, istest } = this.form1
                if (!sensor_id) {
                    this.$message.info('选择测点')
                    return
                }
                this.thrConfig.config = mergeConfigs(this.thrConfig.config, this.form1)

                this.edit({
                    sensor_id,
                    id,
                    channel: direction_sensor,
                    channel,
                    istest,
                    config: this.thrConfig,
                })
            }
        },
        handleScopedChange(e) {
            this.treeData = []
            this.$set(this, 'devices', [])
        },
        getTrouble() {
            return requestApi('post', 'trouble/getlist', { page: 1, size: 9999 }).then((res) => {
                if (res.data.code == 0) {
                    this.troubleList = formatData(res.data.data)
                }
            })
        },
        getSensor(id) {
            return requestApi('get', `device/getSensors?id=${id}`).then((res) => {
                if (res.data.code == 0) {
                    this.sensors = res.data.data
                } else this.sensors = []
            })
        },
        initConfig() {
            this.dialogConfig = deepClone(dialogConfig)
            this.dialogConfig[0].options = this.backstageData
            this.getTrouble().then((res) => {
                this.dialogConfig[1].options = this.troubleList
            })
            this.dialogConfig[0].onChange = (val) => this.handleScopedChange(val)
        },
    },
    created() {},
}
</script>

<style lang="less" scoped>
.dialog {
    .table {
        .row {
            display: flex;
            height: 20px;
            line-height: 20px;
            justify-content: space-around;
            margin-bottom: 10px;
        }

        .ths {
            width: 100%;
            max-height: 40vh;
            // background-color: aliceblue;
            display: flex;
            overflow-y: auto;
            justify-content: space-around;
            margin-bottom: 4px;
        }
    }

    .sensor_table {
        max-height: 14vh;
        border-collapse: collapse;
        width: 90%;
        margin-left: 5%;
        border: 1px solid #007bff;
        border-radius: 4px;

        th,
        td {
            padding: 8px;
            border-bottom: 1px solid #007bff;
        }

        tr {
            color: rgb(130, 187, 237) !important;
            display: flex;
            width: 100%;

            th {
                width: 200px;
                height: 24px;
                line-height: 24px;
                font-weight: bold;
            }

            th:nth-child(1),
            td:nth-child(1) {
                width: 100%;
            }

            // th:nth-child(3),
            // td:nth-child(3),
            // th:nth-child(2),
            // td:nth-child(2) {
            //     width: 40%;
            //     display: flex;
            //     align-items: middle;

            //     .el-input {
            //         .el-input__inner {
            //             height: 30px !important;
            //         }
            //     }

            // }

            td {
                height: 40px !important;
                line-height: 40px !important;
                text-align: center;
            }
        }
    }
}
</style>
